package com.glsc.ngateway.platform.service.glres;

import cn.hutool.core.collection.CollectionUtil;
import com.glsc.ngateway.common.api.common.utils.PageUtil;
import com.glsc.ngateway.common.api.platform.dto.user.PlatformUserDto;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.glres.GlscSystemAuth;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.glres.GlscSystemResource;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.glres.GlscSystemTeam;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.glres.GlscSystemResourceRepository;
import com.glsc.ngateway.platform.service.UserService;
import com.glsc.ngateway.platform.utils.SpecificationUtil;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

@Service
public class GlscSystemResService {

    @Resource
    private GlscSystemResourceRepository glscSystemResourceRepository;

    @Resource
    private GlscSystemTeamService glscSystemTeamService;

    @Resource
    private UserService userService;

    @Resource
    private GlscSystemAuthService glscSystemAuthService;

    /**
     * 分页查找
     *
     * @param pageNo
     * @param pageSize
     * @param param
     * @return
     */
    public Page<GlscSystemResource> page(int pageNo, int pageSize, Map<String, Object> param) {
        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "createTime";

        pageNo = PageUtil.initPageNo(pageNo);
        pageSize = PageUtil.initPageSize(pageSize);

        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, direction, sort);
        Page<GlscSystemResource> page = glscSystemResourceRepository.findAll(SpecificationUtil.buildSpecification(param, GlscSystemResource.class), pageable);
        return page;
    }

    public List<GlscSystemResource> listAllSimpleInfo(String systemType) {
        GlscSystemResource build = GlscSystemResource.builder().deleted("N").build();
        if (StringUtils.isNotBlank(systemType)) {
            build.setSystemType(systemType);
        }
        List<GlscSystemResource> list = glscSystemResourceRepository.findAll(Example.of(build));
        return list;
    }

    /**
     * 根据id查找
     *
     * @param id
     * @return
     */
    public GlscSystemResource findById(Integer id) {

        Optional<GlscSystemResource> optional = glscSystemResourceRepository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    /**
     * 保存
     *
     * @param obj
     * @return
     */
    @Transactional
    public GlscSystemResource save(GlscSystemResource obj, PlatformUserDto user) {
        List<GlscSystemAuth> glscSystemAuths = Lists.newArrayList();
        if (Objects.nonNull(obj.getId())) {
            GlscSystemResource oldSystemInfo = findById(obj.getId());
            glscSystemAuths = glscSystemAuthService.listBySysIdAndUserOaAccount(oldSystemInfo.getId(), oldSystemInfo.getSystemManageOaAccount());
        }
        GlscSystemResource system = glscSystemResourceRepository.save(obj);

        if (StringUtils.isNotBlank(obj.getSystemManageOaAccount())) {
            List<GlscSystemTeam> teams = glscSystemTeamService.findBySysIdAndUserType(obj.getId(), "manageA");
            if (CollectionUtil.isEmpty(teams) || !teams.get(0).getUserOaAccount().equals(obj.getSystemManageOaAccount())) {
                PlatformUserDto manageUser = userService.findByUsername(obj.getSystemManageOaAccount());

                //维护项目经理人员信息
                GlscSystemTeam manageA = GlscSystemTeam.builder().systemId(system.getId()).userType("manageA").userOaAccount(obj.getSystemManageOaAccount())
                        .userId(manageUser.getId()).userName(manageUser.getName()).deleted("N").build();
                glscSystemTeamService.save(manageA);
                if (CollectionUtil.isNotEmpty(teams) && !obj.getSystemManageOaAccount().equals(teams.get(0).getUserOaAccount())) {
                    GlscSystemTeam glscSystemTeam = teams.get(0);
                    glscSystemTeam.setDeleted("Y");
                    glscSystemTeamService.save(glscSystemTeam);
                }

                //维护项目经理权限信息
                if (CollectionUtil.isEmpty(glscSystemAuthService.listBySysIdAndUserOaAccount(system.getId(), system.getSystemManageOaAccount()))) {
                    GlscSystemAuth auth = GlscSystemAuth.builder().systemId(system.getId()).userId(manageUser.getId()).userName(manageUser.getName())
                            .deleted("N").userOaAccount(obj.getSystemManageOaAccount()).validityType("1").build();
                    glscSystemAuthService.save(auth);
                }
                if (!user.getUsername().equals(manageUser.getUsername())) {
                    GlscSystemAuth authCreate = GlscSystemAuth.builder().systemId(system.getId()).userId(user.getId()).userName(user.getName())
                            .deleted("N").userOaAccount(user.getUsername()).validityType("1").build();
                    glscSystemAuthService.save(authCreate);
                }

                if (CollectionUtil.isNotEmpty(glscSystemAuths)) {
                    GlscSystemAuth glscSystemAuth = glscSystemAuths.get(0);
                    glscSystemAuth.setDeleted("Y");
                    glscSystemAuthService.save(glscSystemAuth);
                }
            }
        }
        return system;
    }

    /**
     * 根据id删除
     *
     * @param id
     */
    public void delete(Integer id) {
        glscSystemResourceRepository.deleteById(id);
    }
}
